﻿using System;
using System.Windows.Forms;
using CoreMobile.bce;
using ERIMobileL.oo;
using Opticon.Bcrctl;
using CoreMobile.sec;
using CoreMobile.cfg;
using ERIMobileL.cfg;

namespace ERIMobileL.ui
{
    public partial class LoginForm : Form, IBCENotifiable
    {
        private BCEReader reader;
        private static string VALID_CODE = "easy";
        private static string VALID_CFG_CODE = "1234";
        private Person auxiliar;
        private SettingsManager<ELSettings> settingsManager;

        public LoginForm()
        {
            InitializeComponent();
            
            reader = BCEReader.getReaderWith(this);
            settingsManager = SettingsManager<ELSettings>.get();

            /*if ( ! DeviceIDValidator.isValid("nil"))
            {
                MessageBox.Show("No se puede acceder a la aplicacion");
                Application.Exit();
            }*/
        }

        private void initTurnoMenu_Click(object sender, EventArgs e)
        {
            if(auxiliar==null)
            {
                MessageBox.Show("Debe ingresar un usuario");
                return;
            }
            if(string.IsNullOrEmpty(codigo.Text) ||
                codigo.Text!=VALID_CODE)
            {
                MessageBox.Show("Debe ingresar codigo valido");
                return;
            }

            (new ERIForm()).Show();
            this.Hide();
            reader.BarcodeDecoder.DataHandler -= this.receiverDataFromReader;
            //this.Dispose();
        }

        // exit

        public void receiverDataFromReader(object sender, BarcodeDecoder.ScanEventArgs e)
        {
            string data=reader.preProcess(e);

            //MessageBox.Show(data);

            if(string.IsNullOrEmpty(data)) return;
            
            if(e.CodeType != BarcodeDecoder.CodeIdTypes.PDF417)
            {
                MessageBox.Show("Necesita leer un CI del Reg. Civil");
                return;
            }

            auxiliar=new Person(BCEReader.decodePDF417RegCivil(data)[0]); //rut
            this.usuario.Text = auxiliar.ppRut();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void configMenuItem_Click(object sender, EventArgs e)
        {
            if (this.codigo.Text!=VALID_CFG_CODE)
            {
                MessageBox.Show("Codigo cfg invalido");
                return;
            }

            var cfg=new ConfigForm();
            cfg.CodeListArea.Text = settingsManager.Settings.getCodes(); 
            if(DialogResult.OK == cfg.ShowDialog())
            {
                settingsManager.Settings.parseFrom(cfg.CodeListArea.Text);
                settingsManager.save();
            }
        }
    }
}